package example.echo;

import javax.net.ssl.SSLException;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

public class EchoClient {
	private static final int PORT  = 9000;
	private static final String HOST  = "127.0.0.1";
	static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));
	public static void main(String[] args) {
		 boolean ssl = System.getProperty("ssl") != null;
	 
		 
		//sslcontext
		SslContext sslctx = null ;
		try {
			if(ssl){
				sslctx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
						.build() ;
			}else{
				sslctx = null;
			}
		} catch (SSLException e) {
			e.printStackTrace();
		}
		
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap().group(workerGroup)
					.channel(NioSocketChannel.class)
					.option(ChannelOption.TCP_NODELAY, true)
					.handler(new ChannelInitializer<SocketChannel>() {

						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							 ChannelPipeline pipeline = ch.pipeline();
							pipeline.addLast(new EchoClientHander());
							;
						}
						
					});
			//conn
			ChannelFuture f = b.connect(HOST, PORT).sync();
			System.out.println("client start");
			//wait until the connection is closed;
			f.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			workerGroup.shutdownGracefully();
		}
		
	}
	
	 
}
